package xyz.mumuwei.youthcourseserver.intereptor;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import xyz.mumuwei.youthcourseserver.common.lang.Const;
import xyz.mumuwei.youthcourseserver.common.lang.Result;
import xyz.mumuwei.youthcourseserver.utils.JwtTokenUtil;
import xyz.mumuwei.youthcourseserver.utils.RedisUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author mumuwei
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        if (RequestMethod.OPTIONS.name().equals(request.getMethod())) {
            return true;
        }

        String token = request.getHeader("Authorization");
        // 判断请求是否携带 token
        if (token == null || "".equals(token)) {
            returnJson(response, Result.fail(Const.PARAM_FAIL_CODE, Const.PARAM_FAIL_MSG));
            return false;
        }
        // 判断 token 是否匹配
        boolean flag = JwtTokenUtil.verify(token);
        if(!flag) {
            return false;
        }
        request.setAttribute("uid", JwtTokenUtil.getUserId(token));
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    private void returnJson(HttpServletResponse response, Result result) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try (PrintWriter writer = response.getWriter()) {
            writer.print(JSON.toJSON(result));
        }
    }
}
